<script setup>
import { ref, reactive } from 'vue'

// 当前激活的标签页
const activeTab = ref('login')

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: ''
})

// 注册表单数据
const registerForm = reactive({
  username: '',
  name: '',
  password: '',
  confirmPassword: ''
})

// 登录状态
const loginLoading = ref(false)
const loginError = ref('')

// 注册状态
const registerLoading = ref(false)
const registerError = ref('')
const registerSuccess = ref('')

// 登录提交
async function submitLogin() {
  loginError.value = ''
  loginLoading.value = true

  try {
    const resp = await fetch('/api/auth/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: loginForm.username,
        password: loginForm.password
      })
    })

    const data = await resp.json()

    if (!resp.ok || data.code !== 0) {
      throw new Error(data.message || '登录失败')
    }

    const token = data.data?.token || ''
    if (token) {
      // 保存登录态关键信息，供全局使用
      localStorage.setItem('token', token)
      if (data.data?.id !== undefined) {
        localStorage.setItem('userId', String(data.data.id))
      }
      localStorage.setItem('username', data.data?.username || '')
      localStorage.setItem('name', data.data?.name || '')
      localStorage.setItem('avatarUrl', data.data?.avatarUrl || '')


      // 添加登录成功动画
      document.querySelector('.auth-card').classList.add('success')

      setTimeout(() => {
      location.href = '/'
      }, 800)

      return
    }
  } catch (e) {
    loginError.value = e.message || '请求失败'
  } finally {
    loginLoading.value = false
  }
}

// 注册提交
async function submitRegister() {
  registerError.value = ''
  registerSuccess.value = ''
  registerLoading.value = true

  // 验证密码确认
  if (registerForm.password !== registerForm.confirmPassword) {
    registerError.value = '两次输入的密码不一致'
    registerLoading.value = false
    return
  }

  // 验证密码长度
  if (registerForm.password.length < 6) {
    registerError.value = '密码长度至少6位（建议8-20位，包含大小写字母、数字和特殊字符）'
    registerLoading.value = false
    return
  }

  try {
    const resp = await fetch('/api/auth/register', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: registerForm.username,
        name: registerForm.name,
        password: registerForm.password
      })
    })

    const data = await resp.json()

    if (!resp.ok || data.code !== 0) {
      throw new Error(data.message || '注册失败')
    }

    registerSuccess.value = '注册成功！请使用新账号登录。出于安全考虑，请在首次登录后尽快前往“系统管理 → 修改密码”设置更强的密码，并在“个人信息”完善邮箱、手机号、部门、职位等资料。'

    // 清空表单
    registerForm.username = ''
    registerForm.name = ''
    registerForm.password = ''
    registerForm.confirmPassword = ''

    // 3秒后自动切换到登录页
    setTimeout(() => {
      activeTab.value = 'login'
      registerSuccess.value = ''
    }, 3000)

  } catch (e) {
    registerError.value = e.message || '请求失败'
  } finally {
    registerLoading.value = false
  }
}
</script>

<template>
  <div class="login-container">
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="circle circle-1"></div>
      <div class="circle circle-2"></div>
      <div class="circle circle-3"></div>
    </div>

    <!-- 登录/注册卡片 -->
    <div class="auth-card">
      <!-- Logo区域 -->
      <div class="logo-section">
        <div class="logo-icon">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M12 2L2 7L12 12L22 7L12 2Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M2 17L12 22L22 17" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M2 12L12 17L22 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </div>
        <h1 class="system-title">元启 ERP</h1>
        <p class="system-subtitle">企业资源管理系统</p>
      </div>

      <!-- 切换标签 -->
      <div class="tab-container">
        <button
          @click="activeTab = 'login'"
          class="tab-button"
          :class="{ 'active': activeTab === 'login' }"
        >
          登录
        </button>
        <button
          @click="activeTab = 'register'"
          class="tab-button"
          :class="{ 'active': activeTab === 'register' }"
        >
          注册
        </button>
      </div>

      <!-- 登录表单 -->
      <form v-if="activeTab === 'login'" @submit.prevent="submitLogin" class="auth-form">
        <div class="form-group">
          <div class="input-wrapper">
            <div class="input-icon">
              <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M20 21V19C20 17.9391 19.5786 16.9217 18.8284 16.1716C18.0783 15.4214 17.0609 15 16 15H8C6.93913 15 5.92172 15.4214 5.17157 16.1716C4.42143 16.9217 4 17.9391 4 19V21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <rect x="9" y="7" width="6" height="6" rx="3" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </div>
            <input
              v-model="loginForm.username"
              type="text"
              placeholder="请输入用户名"
              class="form-input"
              :class="{ 'error': loginError && !loginForm.username }"
              required
            />
          </div>
        </div>

        <div class="form-group">
          <div class="input-wrapper">
            <div class="input-icon">
              <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M19 11H5M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M12 7V12L15 15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </div>
            <input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              class="form-input"
              :class="{ 'error': loginError && !loginForm.password }"
              required
            />
          </div>
        </div>

        <!-- 登录错误提示 -->
        <div v-if="loginError" class="error-message">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
            <line x1="15" y1="9" x2="9" y2="15" stroke="currentColor" stroke-width="2"/>
            <line x1="9" y1="9" x2="15" y2="15" stroke="currentColor" stroke-width="2"/>
          </svg>
          {{ loginError }}
        </div>

        <!-- 登录按钮 -->
        <button
          type="submit"
          :disabled="loginLoading"
          class="auth-button"
          :class="{ 'loading': loginLoading }"
        >
          <span v-if="!loginLoading" class="button-text">登录系统</span>
          <span v-else class="loading-spinner">
            <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="31.416" stroke-dashoffset="31.416">
                <animate attributeName="stroke-dashoffset" values="0;31.416" dur="1s" repeatCount="indefinite"/>
              </circle>
            </svg>
          </span>
        </button>
      </form>

      <!-- 注册安全提示 -->
      <div v-if="activeTab === 'register'" class="register-tips">
        <h4>注册后建议：</h4>
        <ul>
          <li>首次登录后，立即前往「系统管理 → 修改密码」设置更高安全系数的密码（建议 8-20 位，包含大小写字母、数字与特殊字符）。</li>
          <li>在「系统管理 → 个人信息」完善邮箱、手机号、部门、职位等资料，便于后续通知与权限配置。</li>
        </ul>
      </div>

      <!-- 注册表单 -->
      <form v-if="activeTab === 'register'" @submit.prevent="submitRegister" class="auth-form">
        <div class="form-group">
          <div class="input-wrapper">
            <div class="input-icon">
              <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M20 21V19C20 17.9391 19.5786 16.9217 18.8284 16.1716C18.0783 15.4214 17.0609 15 16 15H8C6.93913 15 5.92172 15.4214 5.17157 16.1716C4.42143 16.9217 4 17.9391 4 19V21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <rect x="9" y="7" width="6" height="6" rx="3" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </div>
            <input
              v-model="registerForm.username"
              type="text"
              placeholder="请输入用户名"
              class="form-input"
              :class="{ 'error': registerError && !registerForm.username }"
              required
            />
          </div>
        </div>

        <div class="form-group">
          <div class="input-wrapper">
            <div class="input-icon">
              <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M16 7C16 9.20914 14.2091 11 12 11C9.79086 11 8 9.20914 8 7C8 4.79086 9.79086 3 12 3C14.2091 3 16 4.79086 16 7Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M12 14C8.13401 14 5 17.134 5 21H19C19 17.134 15.866 14 12 14Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </div>
            <input
              v-model="registerForm.name"
              type="text"
              placeholder="请输入姓名"
              class="form-input"
              :class="{ 'error': registerError && !registerForm.name }"
              required
            />
          </div>
        </div>

        <div class="form-group">
          <div class="input-wrapper">
            <div class="input-icon">
              <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M19 11H5M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M12 7V12L15 15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </div>
            <input
              v-model="registerForm.password"
              type="password"
              placeholder="请输入密码"
              class="form-input"
              :class="{ 'error': registerError && !registerForm.password }"
              required
            />
          </div>
        </div>

        <div class="form-group">
          <div class="input-wrapper">
            <div class="input-icon">
              <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M19 11H5M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M12 7V12L15 15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </div>
            <input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="请确认密码"
              class="form-input"
              :class="{ 'error': registerError && !registerForm.confirmPassword }"
              required
            />
          </div>
        </div>

        <!-- 注册错误提示 -->
        <div v-if="registerError" class="error-message">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
            <line x1="15" y1="9" x2="9" y2="15" stroke="currentColor" stroke-width="2"/>
            <line x1="9" y1="9" x2="15" y2="15" stroke="currentColor" stroke-width="2"/>
          </svg>
          {{ registerError }}
        </div>

        <!-- 注册成功提示 -->
        <div v-if="registerSuccess" class="success-message">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <polyline points="22,4 12,14.01 9,11.01" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          {{ registerSuccess }}
        </div>

        <!-- 注册按钮 -->
        <button
          type="submit"
          :disabled="registerLoading"
          class="auth-button"
          :class="{ 'loading': registerLoading }"
        >
          <span v-if="!registerLoading" class="button-text">注册账号</span>
          <span v-else class="loading-spinner">
            <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="31.416" stroke-dashoffset="31.416">
                <animate attributeName="stroke-dashoffset" values="0;31.416" dur="1s" repeatCount="indefinite"/>
              </circle>
            </svg>
          </span>
      </button>
      </form>

      <!-- 底部信息 -->
      <div class="footer-info">
        <p>© 2024 YuanQi ERP System. All rights reserved.</p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
  padding: 20px;
}

/* 背景装饰 */
.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.circle-1 {
  width: 200px;
  height: 200px;
  top: -100px;
  right: -100px;
  animation-delay: 0s;
}

.circle-2 {
  width: 150px;
  height: 150px;
  bottom: -75px;
  left: -75px;
  animation-delay: 2s;
}

.circle-3 {
  width: 100px;
  height: 100px;
  top: 50%;
  left: -50px;
  animation-delay: 4s;
}

@keyframes float {
  0%, 100% { transform: translateY(0px) rotate(0deg); }
  50% { transform: translateY(-20px) rotate(180deg); }
}

/* 认证卡片 */
.auth-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 24px;
  padding: 48px;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.15);
  width: 100%;
  max-width: 420px;
  position: relative;
  z-index: 1;
  transition: all 0.3s ease;
}

.auth-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 30px 60px rgba(0, 0, 0, 0.2);
}

.auth-card.success {
  animation: successPulse 0.8s ease-out;
}

@keyframes successPulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}

/* Logo区域 */
.logo-section {
  text-align: center;
  margin-bottom: 32px;
}

.logo-icon {
  width: 64px;
  height: 64px;
  margin: 0 auto 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.logo-icon svg {
  width: 32px;
  height: 32px;
}

.system-title {
  font-size: 28px;
  font-weight: 700;
  color: #2d3748;
  margin: 0 0 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.system-subtitle {
  font-size: 16px;
  color: #718096;
  margin: 0;
  font-weight: 500;
}

/* 切换标签 */
.tab-container {
  display: flex;
  background: #f7fafc;
  border-radius: 12px;
  padding: 4px;
  margin-bottom: 32px;
}

.tab-button {
  flex: 1;
  padding: 12px 24px;
  border: none;
  background: transparent;
  color: #718096;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.tab-button.active {
  background: white;
  color: #667eea;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.tab-button:hover:not(.active) {
  color: #4a5568;
}

/* 表单样式 */
.auth-form {
  margin-bottom: 32px;
}

.form-group {
  margin-bottom: 20px;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-icon {
  position: absolute;
  left: 16px;
  color: #a0aec0;
  z-index: 2;
}

.input-icon svg {
  width: 20px;
  height: 20px;
}

.form-input {
  width: 100%;
  padding: 16px 16px 16px 48px;
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  font-size: 16px;
  transition: all 0.3s ease;
  background: white;
}

.form-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
  transform: translateY(-2px);
}

.form-input.error {
  border-color: #f56565;
  box-shadow: 0 0 0 3px rgba(245, 101, 101, 0.1);
}

.form-input::placeholder {
  color: #a0aec0;
}

/* 错误提示 */
.error-message {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #f56565;
  font-size: 14px;
  margin-bottom: 20px;
  padding: 12px 16px;
  background: rgba(245, 101, 101, 0.1);
  border-radius: 8px;
  border-left: 4px solid #f56565;
}

.error-message svg {
  width: 16px;
  height: 16px;
  flex-shrink: 0;
}

/* 成功提示 */
.success-message {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #38a169;
  font-size: 14px;
  margin-bottom: 20px;
  padding: 12px 16px;
  background: rgba(56, 161, 105, 0.1);
  border-radius: 8px;
  border-left: 4px solid #38a169;
}

.success-message svg {
  width: 16px;
  height: 16px;
  flex-shrink: 0;
}

/* 注册安全提示 */
.register-tips {
  margin-top: 8px;
  padding: 12px 14px;
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
}
.register-tips h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #2d3748;
}
.register-tips ul {
  margin: 0;
  padding-left: 18px;
  color: #4a5568;
  font-size: 13px;
  line-height: 1.6;
}

/* 认证按钮 */
.auth-button {
  width: 100%;
  padding: 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.auth-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 10px 25px rgba(102, 126, 234, 0.3);
}

.auth-button:active:not(:disabled) {
  transform: translateY(0);
}

.auth-button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.auth-button.loading {
  background: linear-gradient(135deg, #a0aec0 0%, #718096 100%);
}

.button-text {
  display: block;
}

.loading-spinner {
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-spinner svg {
  width: 24px;
  height: 24px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 底部信息 */
.footer-info {
  text-align: center;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #e2e8f0;
}

.footer-info p {
  font-size: 12px;
  color: #a0aec0;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .auth-card {
    padding: 32px 24px;
    margin: 20px;
  }

  .system-title {
    font-size: 24px;
  }

  .form-input {
    padding: 14px 14px 14px 44px;
    font-size: 16px;
  }

  .auth-button {
    padding: 14px;
  }

  .tab-button {
    padding: 10px 20px;
    font-size: 14px;
  }
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .auth-card {
    background: rgba(26, 32, 44, 0.95);
    color: white;
  }

  .system-title {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
  }

  .system-subtitle {
    color: #a0aec0;
  }

  .form-input {
    background: rgba(45, 55, 72, 0.8);
    border-color: #4a5568;
    color: white;
  }

  .form-input:focus {
    border-color: #667eea;
  }

  .tab-container {
    background: rgba(45, 55, 72, 0.8);
  }

  .tab-button.active {
    background: rgba(102, 126, 234, 0.2);
  }
}
</style>


